package cn.ysym.tcsy;

import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import cn.ysym.dao.OfflineStockDao;
import cn.ysym.dao.OfflineSumDao;
import cn.ysym.dao.ProductDao;
import cn.ysym.dao.SettingDao;
import cn.ysym.model.OfflineStock;
import cn.ysym.model.OfflineSum;
import cn.ysym.model.Product;
import cn.ysym.model.Setting;
import cn.ysym.util.CommonUtil;

public class OfflineStockActivity extends AppCompatActivity {

    @BindView(R.id.etBatch)
    EditText etBatch;
    @BindView(R.id.lvBatch)
    ListView lvBatch;
    private SettingDao settingDao;
    private ProductDao productDao;
    private OfflineSumDao offlineSumDao;
    private OfflineStockDao offlineStockDao;
    private ProgressBar progressBar;
    private EditText etProduct;
    private ListView lvProduct;
    private CheckBox cbVirtualBig;
    private EditText etCode;
    private OfflineSum curSum;
    private TextView tvSuccNum;
    private int succNum = 0;
    private ListView lvResult;
    private ArrayAdapter<String> resultAdapter;
    private String productId;   //选中产品id

    private UpDataTask upDataTask;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_offline_stock);
        ButterKnife.bind(this); //绑定butterKnife插件
        setTitle("离线入库");

        settingDao = new SettingDao(this);
        productDao = new ProductDao(this);
        offlineSumDao = new OfflineSumDao(this);
        offlineStockDao = new OfflineStockDao(this);

        progressBar = (ProgressBar) findViewById(R.id.progressBarOnline);
        etProduct = (EditText) findViewById(R.id.etProduct);
        lvProduct = (ListView) findViewById(R.id.lvProduct);
        lvProduct.setVerticalScrollBarEnabled(true);

        etProduct.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    ArrayAdapter<String> productAdapter = new ArrayAdapter<String>(OfflineStockActivity.this, R.layout.list_view);
                    List<Product> ps = productDao.query("");
                    for (Product p : ps) {
                        productAdapter.add(CommonUtil.formatStr(p.getProductName()));
                    }
                    lvProduct.setAdapter(productAdapter);
                    lvProduct.setVisibility(View.VISIBLE);
                } else {
                    lvProduct.setVisibility(View.GONE);
                }
            }
        });

        etProduct.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                ArrayAdapter<String> productAdapter = new ArrayAdapter<String>(OfflineStockActivity.this, R.layout.list_view);
                List<Product> ps = productDao.query(s.toString());
                for (Product p : ps) {
                    productAdapter.add(CommonUtil.formatStr(p.getProductName()));
                }
                lvProduct.setAdapter(productAdapter);
                lvProduct.setVisibility(View.VISIBLE);
            }
        });

        lvProduct.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                String text = parent.getAdapter().getItem(position).toString();
                etProduct.setText(text);
                lvProduct.setVisibility(View.GONE);
                etCode.requestFocus();
                etBatch.setText("");
            }
        });

        cbVirtualBig = (CheckBox) findViewById(R.id.ckVirtualBig);

        etCode = (EditText) findViewById(R.id.etCode);
        etCode.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_ENTER) {
                    if (upDataTask == null) {
                        progressBar.setVisibility(View.VISIBLE);
                        String productId = etProduct.getText().toString();
                        productId = productId.replace("\n", "");
                        int tIndex = productId.indexOf(" ");
                        if (tIndex > 0) productId = productId.substring(0, tIndex);

                        String virtualBig = "0";
                        if (cbVirtualBig.isChecked()) {
                            virtualBig = "1";
                        }

                        String code = CommonUtil.cleanCode(etCode.getText().toString());
                        etCode.setText(code);

                        String procDesc = "入库";
                        Product product = productDao.queryById(productId);
                        if (product != null) procDesc += "：" + product.getProductName();

                        String batchId = etBatch.getText().toString();

                        upDataTask = new UpDataTask(productId, virtualBig, code, procDesc, batchId);
                        upDataTask.execute((Void) null);
                    }
                }
                return false;
            }
        });

        tvSuccNum = (TextView) findViewById(R.id.tvSuccNum);
        //扫码记录
        lvResult = (ListView) findViewById(R.id.lvResult);
        resultAdapter = new ArrayAdapter<String>(OfflineStockActivity.this, R.layout.list_view);
        lvResult.setAdapter(resultAdapter);
    }

    public class UpDataTask extends AsyncTask<Void, Void, Boolean> {
        private String productId;
        private String virtualBig;
        private String code;
        private String procDesc;
        private String batchId;

        public UpDataTask(String productId, String virtualBig, String code, String procDesc, String batchId) {
            this.productId = productId;
            this.virtualBig = virtualBig;
            this.code = code;
            this.procDesc = procDesc;
            this.batchId = batchId;
        }

        @Override
        protected Boolean doInBackground(Void... params) {
            if (offlineStockDao.isExist(code)) return false;
            else {
                if (curSum == null) {
                    Setting userName = settingDao.query("userName");
                    curSum = new OfflineSum();
                    curSum.setAccount(userName.getSettingValue());
                    curSum.setUpFailNum(0);
                    curSum.setUpSuccNum(0);
                    curSum.setProcDesc(procDesc);
                    curSum.setProcNum(1);
                    curSum.setProcType("0");
                    offlineSumDao.insert(curSum);

                    curSum = offlineSumDao.getLast();
                } else {
                    curSum.setProcNum(curSum.getProcNum() + 1);
                    offlineSumDao.update(curSum);
                }

                OfflineStock os = new OfflineStock();
                os.setProductId(productId);
                os.setBigCode("");
                os.setCode(code);
                os.setVirtualBig(virtualBig);
                os.setSumId(curSum.getId());
                os.setUpSucc("0");
                os.setScanTime(CommonUtil.getDateTimeStr("yyyyMMddHHmmss"));
                offlineStockDao.insert(os);

                return true;
            }
        }

        @Override
        protected void onPostExecute(final Boolean ret) {
            upDataTask = null;
            progressBar.setVisibility(View.GONE);

            if (ret) {
                succNum++;
                tvSuccNum.setText(String.valueOf(succNum));
                resultAdapter.add(code);
            } else {
                CommonUtil.playSound(OfflineStockActivity.this);
                Toast.makeText(getApplicationContext(), "已扫码", Toast.LENGTH_SHORT).show();
            }

            etCode.setText("");
            etCode.requestFocus();
        }

    }
}
